package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
@Transactional
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
  //  @Cacheable(value = "category_dish", key = "#searchDto.page", condition = "#searchDto.page ==1")
    public PageResult findPage(DishPageQueryDTO searchDto) {
        //1.计算分页其实索引值
        Integer page = searchDto.getPage();
        Integer pageSize = searchDto.getPageSize();

        PageHelper.startPage(page, pageSize);


        Page<DishVO> dish = dishMapper.findPage(searchDto);//后面 limit 0,10

        long total = dish.getTotal();//总记录数
        int pages = dish.getPages();//总页数
        List result = dish.getResult(); //本页数据

        //4.封装PageResultVo
        PageResult pageResultVo = new PageResult();
        //PageResult.setTotal(total);
        //PageResult.setRecords
        pageResultVo.setTotal(total);
        pageResultVo.setRecords(result);
        // Result re = new Result();
        return pageResultVo;
    }

    @Override
 //   @CacheEvict(value = "category_dish", allEntries = true)
    public Integer deleteById(List<Long> ids) {
        List<SetmealDish> setmealDishes = setmealDishMapper.seleteById(ids);
        if (setmealDishes.size() != 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        List<Dish> byIds = dishMapper.findByIds(ids);
        for (Dish byId : byIds) {
            if (byId.getStatus() != 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        dishFlavorMapper.deleteById(ids);
        return dishMapper.deleteById(ids);

    }

    @Override
  //  @CacheEvict(value = "category_dish", allEntries = true)
    public Integer save(DishDTO dto) {
        Dish dish = new Dish();

        BeanUtils.copyProperties(dto, dish);

        //向菜品表插入1条数据
        Integer save = dishMapper.save(dish);//后绪步骤实现

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            Integer insert = dishFlavorMapper.insert(flavors);//后绪步骤实现
        }
        return save;
    }

    @Override
    public DishVO findById(Long id) {
        return dishMapper.findById(id);
    }

    @Override
  //  @CacheEvict(value = "category_dish", allEntries = true)
    public Integer updateDish(DishDTO dto) {
        Long id = dto.getId();
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        if (ids.size() > 0) {
            dishFlavorMapper.deleteById(ids);
            dto.getFlavors().forEach(flavors -> flavors.setDishId(dto.getId()));
            dishFlavorMapper.insert(dto.getFlavors());
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        return dishMapper.updateDish(dish);
    }

    @Override
    public Result changeStatus(Integer id, Integer status) {

        Dish dish = new Dish();
        dish.setId(Long.valueOf(id));
        dish.setStatus(status);
//        查询当前菜品是否包含在套餐里
        int i1 = dishMapper.dishIsInSetmeal(id);
        int i = 0;
        if (i1 == 0) {
            i = dishMapper.updateDishStatus(dish);
        } else {
            i = dishMapper.updateStatus(dish);
        }

        if (i > 0) {
            return Result.success();
        } else {
            return Result.error(MessageConstant.UPDATEINFO_FAILED);
        }
    }


    //@Cacheable(value = "category_dish", key = "'#categoryId'")
    @Override
    public List<DishVO> findByCategoryId(String categoryId) {
        /*List<DishVO> dishVOS = (List<DishVO>) redisTemplate.opsForValue().get("category" + categoryId + ":dishList");
        if (dishVOS == null) {*/
          List<DishVO>   dishVOS = dishMapper.findByCategoryId(categoryId);
           // redisTemplate.opsForValue().set("category" + categoryId + ":dishList", dishVOS);
       // }
        return dishVOS;
    }

    @Override
    public List<DishVO> findDishByCategoryId(Integer categoryId) {
        return dishMapper.findDishByCategoryId(categoryId);
    }

}
